import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from "/@/utils/authFunction";
import { useRouter } from 'vue-router';

export default function ({ crudExpose }: { crudExpose: CrudExpose }): CreateCrudOptionsRet {
    const router = useRouter();
    
    const pageRequest = async (query: any) => {
        return await api.GetList(query);
    };
    const editRequest = async ({ form, row }: EditReq) => {
        if (row.id) {
            form.id = row.id;
        }
        return await api.UpdateObj(form);
    };
    const delRequest = async ({ row }: DelReq) => {
        return await api.DelObj(row.id);
    };
    const addRequest = async ({ form }: AddReq) => {
        return await api.AddObj(form);
    };

    const exportRequest = async (query: UserPageQuery) => {
        return await api.exportData(query)
    };

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    export: {
                        show: auth('Supplier:Export'),
                        text: "导出",
                        title: "导出",
                        click() {
                            return exportRequest(crudExpose.getSearchFormData())
                        }
                    },
                    add: {
                        show: auth('Supplier:Create'),
                    },
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 250,
                buttons: {
                    detail: {
                        text: '详情',
                        order: 0,
                        show: auth('Supplier:Retrieve'),
                        click: ({ row }) => {
                            router.push(`/supplier/detail/${row.id}`);
                        }
                    },
                    view: {
                        type: 'text',
                        order: 1,
                        show: auth('Supplier:Retrieve')
                    },
                    edit: {
                        type: 'text',
                        order: 2,
                        show: auth('Supplier:Update')
                    },
                    copy: {
                        type: 'text',
                        order: 3,
                        show: auth('Supplier:Copy')
                    },
                    remove: {
                        type: 'text',
                        order: 4,
                        show: auth('Supplier:Delete')
                    },
                },
            },
            columns: {
                name: {
                    title: '供应商名称',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 120,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '供应商名称必填' }],
                        component: {
                            placeholder: '请输入供应商名称',
                        },
                    },
                },
                code: {
                    title: '供应商编码',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 100,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '供应商编码必填' }],
                        component: {
                            placeholder: '请输入供应商编码',
                        },
                    },
                },
                contact_person: {
                    title: '联系人',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 100,
                    },
                    form: {
                        rules: [{ required: true, message: '联系人必填' }],
                        component: {
                            placeholder: '请输入联系人',
                        },
                    },
                },
                contact_phone: {
                    title: '联系电话',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 120,
                    },
                    form: {
                        rules: [
                            { required: true, message: '联系电话必填' },
                            { 
                                pattern: /^(1[3-9]\d{9}|0\d{2,3}-\d{7,8})$/,
                                message: '请输入正确的电话格式（手机号或固定电话，固话格式：区号-号码）'
                            }
                        ],
                        component: {
                            placeholder: '请输入联系电话（手机号或固定电话）',
                        },
                    },
                },
                email: {
                    title: '电子邮箱',
                    type: 'input',
                    search: { show: false },
                    column: {
                        minWidth: 150,
                    },
                    form: {
                        component: {
                            placeholder: '请输入电子邮箱',
                        },
                    },
                },
                address: {
                    title: '地址',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 200,
                    },
                    form: {
                        rules: [{ required: true, message: '地址必填' }],
                        component: {
                            placeholder: '请输入地址',
                        },
                    },
                },
                business_scope: {
                    title: '经营范围',
                    type: 'textarea',
                    search: { show: false },
                    column: {
                        minWidth: 200,
                    },
                    form: {
                        component: {
                            placeholder: '请输入经营范围',
                            span: 24,
                        },
                    },
                },
                status: {
                    title: '状态',
                    type: 'dict-switch',
                    search: { show: true },
                    dict: dict({
                        data: [
                            { value: true, label: '启用' },
                            { value: false, label: '禁用' }
                        ]
                    }),
                    column: {
                        minWidth: 80,
                        component: {
                            name: 'el-switch',
                            activeText: '',
                            inactiveText: '',
                            inlinePrompt: true,
                            activeValue: true,
                            inactiveValue: false,
                            onChange: async (value: boolean, row: any) => {
                                if (!row || !row.id) {
                                    console.error('无效的行数据');
                                    crudExpose.doRefresh();
                                    return;
                                }
                                try {
                                    console.log('当前行ID:', row.id);
                                    const updateData = {
                                        id: row.id,
                                        status: value
                                    };
                                    await api.UpdateObj(updateData);
                                } catch (e) {
                                    console.error('更新状态失败:', e);
                                    // 通过 crud 的刷新方法重新加载数据
                                    crudExpose.doRefresh();
                                }
                            }
                        }
                    },
                    form: {
                        value: true,
                        component: {
                            name: 'el-switch',
                            activeText: '',
                            inactiveText: '',
                            inlinePrompt: true,
                            activeValue: true,
                            inactiveValue: false
                        }
                    }
                },
                credit_rating: {
                    title: '信用等级',
                    type: 'dict-select',
                    search: { show: true },
                    dict: dict({
                        data: [
                            { value: 'A', label: 'A级' },
                            { value: 'B', label: 'B级' },
                            { value: 'C', label: 'C级' },
                            { value: 'D', label: 'D级' }
                        ]
                    }),
                    column: {
                        minWidth: 100
                    },
                    form: {
                        component: {
                            name: 'fs-dict-select',
                            placeholder: '请选择信用等级',
                            options: [
                                { value: 'A', label: 'A级' },
                                { value: 'B', label: 'B级' },
                                { value: 'C', label: 'C级' },
                                { value: 'D', label: 'D级' }
                            ]
                        },
                    },
                },
                remarks: {
                    title: '备注',
                    type: 'textarea',
                    search: { show: false },
                    column: {
                        minWidth: 150,
                    },
                    form: {
                        component: {
                            placeholder: '请输入备注',
                            span: 24,
                        },
                    },
                },
            },
        },
    };
} 